package com.xiaoge.web;

import com.xiaoge.config.WebAppConfig;
import com.xiaoge.other.ZhangXiaoInitializer;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;

/**
 * TODO	自己实现spring boot
 *
 * 		1. 内嵌一个tomcat如何启动? JAVA
 * 			Tomcat tomcat = new Tomcat();
 * 			tomcat.start();
 *
 * 		2. 如何把SpringMVC技术整合进来?
 * 			DispatcherServlet
 * 				old:
 * 					spring2.5 web.xml <servlet name class> url
 * 			 	new:
 * 			 		spring4以后springmvc 不需要  web.xml	而是通过如下配置搭建web项目MyInitializer实现WebApplicationInitializer
 * 		3. 如何实现0配置 (不需要xml-----web.xml)?
 * 			web.xml? 干了什么
 * 			1. 配置一个DispatcherServlet
 * 					init spring-mvc.xml
 * 						扫描controller
 * 						json解析 (不必要的)
 * 						视图解析	(不必要的)
 * 					这个功能已经被替代---->servletContext.addServlet()
 * 			2. 配置一个ContextLoaderListener---> 执行spring的初始化 扫描 dao service controller
 * 					这个功能被替代DispatcherServlet servlet = new DispatcherServlet(context);
 * 				todo Tomcat调用SpringServletContainerInitializer下的onStartup方法, 因为它实现了servlet3.0规范ServletContainerInitializer
 * 	 		 	 	而因为SpringServletContainerInitializer类上加了@HandlesTypes(WebApplicationInitializer.class), 它获取找所有该类型的class
 * 	 			  	传入给webAppInitializerClasses, 其中就有我们自己写的MyWebApplicationInitializer, 然后掉它自己的onStartup方法
 *
 *
 * @author <a href="mailto:1330137071@qq.com">Zhang Xiao</a>
 * @since
 */
public class MyInitializer implements ZhangXiaoInitializer {
	@Override
	public void onStartup(ServletContext servletContext) throws ServletException {

		AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
		context.register(WebAppConfig.class);

		DispatcherServlet servlet = new DispatcherServlet(context);
		/**
		 * 相当一传统对的web.xml当中的
		 * <servlet>
		 *     <servlet-class>xxxx</servlet-class>
		 * <servlet/>
		 *
		 * 也相当于servlet3.0提供的@WebServlet
		 */
		ServletRegistration.Dynamic registration = servletContext.addServlet("app", servlet);
		registration.setLoadOnStartup(1);
		registration.addMapping("/app/*");
	}
}
